package popcorn.ticket.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;

import popcorn.ticket.config.AlipayConfigInfo;
import popcorn.ticket.entity.Orders;
import popcorn.ticket.entity.PayInfo;
import popcorn.ticket.entity.Schedule;
import popcorn.ticket.entity.Ticket;
import popcorn.ticket.service.MembersService;
import popcorn.ticket.service.OrdersService;
import popcorn.ticket.service.ScheduleService;
import popcorn.ticket.service.TicketService;

@Controller
public class PayController {
	
	@Autowired
	OrdersService os;
	
	@Autowired
	TicketService ts;
	
	@Autowired
	ScheduleService ss;
	
	@Autowired
	MembersService ms;
	

	static public int scheduleid;
	static public int orderid;
	static public double price;
	
	Logger logger = Logger.getLogger(PayController.class);

	/**
	 * 快捷支付调用支付宝支付接口
	 */
	@RequestMapping("alipaySum")
	public Object alipayIumpSum(PayInfo payInfo, Model model, HttpServletResponse response)
			throws Exception {
		
		orderid = Integer.parseInt(payInfo.getOut_trade_no());
		price = Double.parseDouble(payInfo.getTotal_amount());
		scheduleid = payInfo.getScheduleid();

		
		// 获得初始化的AlipayClient
		AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfigInfo.gatewayUrl, AlipayConfigInfo.app_id,
				AlipayConfigInfo.merchant_private_key, "json", AlipayConfigInfo.charset,
				AlipayConfigInfo.alipay_public_key, AlipayConfigInfo.sign_type);
		// 设置请求参数
		AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
		alipayRequest.setReturnUrl(AlipayConfigInfo.return_url);
		alipayRequest.setNotifyUrl(AlipayConfigInfo.notify_url);
		// 商户订单号，商户网站订单系统中唯一订单号
		String out_trade_no = payInfo.getOut_trade_no();
		// 付款金额，必填,控制器传入参数，需要添加 付款金额，标题，订单信息
		String total_amount = payInfo.getTotal_amount();
		// 订单信息，必填
		String body = "欢迎观看电影《"+payInfo.getCus()+"》";
		// 订单标题
		String subject = payInfo.getCus();

		// 将信息显示在支付页面上
		alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\"," + "\"total_amount\":\"" + total_amount
				+ "\"," + "\"subject\":\"" + subject + "\"," + "\"body\":\"" + body + "\","
				+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
		// 请求
		String result = alipayClient.pageExecute(alipayRequest).getBody();
		
		AlipayConfigInfo.logResult(result);// 记录支付日志
		response.setContentType("text/html; charset=utf-8");
		PrintWriter out = response.getWriter();
		out.print(result);
		return null;
	}

	/**
	 * 调用支付宝退款接口
	 */
	@RequestMapping("alipayRefund")
	public ModelAndView aliRefund(HttpServletResponse response, PayInfo payInfo) {
		logger.debug("get:"+payInfo);
		String result = "";
		String out_trade_no = null;
		try {
			// 获得初始化的AlipayClient
			AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfigInfo.gatewayUrl, AlipayConfigInfo.app_id,
					AlipayConfigInfo.merchant_private_key, "json", AlipayConfigInfo.charset,
					AlipayConfigInfo.alipay_public_key, AlipayConfigInfo.sign_type);
			// 设置请求参数
			AlipayTradeRefundRequest alipayRequest = new AlipayTradeRefundRequest();
			// 商户订单号，商户网站订单系统中唯一订单号
			out_trade_no = payInfo.getOut_trade_no();
			// 支付宝交易号
			String trade_no = payInfo.getTrade_no();
			// 请二选一设置
			// 需要退款的金额，该金额不能大于订单金额，必填
			String refund_amount = payInfo.getRefund().toString();
			// 退款的原因说明
			String refund_reason = payInfo.getRefund_cause();
			// 标识一次退款请求，同一笔交易多次退款需要保证唯一，如需部分退款，则此参数必传
			String out_request_no = payInfo.getRefund_num();
			alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\"," + "\"trade_no\":\"" + trade_no
					+ "\"," + "\"refund_amount\":\"" + refund_amount + "\"," + "\"refund_reason\":\"" + refund_reason
					+ "\"," + "\"out_request_no\":\"" + out_request_no + "\"}");
			// 请求
			result = alipayClient.execute(alipayRequest).getBody();
			AlipayConfigInfo.logResult(result);// 记录支付日志

		} catch (Exception e) {
			e.printStackTrace();
			result = "1";
			response.setContentType("text/html;charset=utf-8");
			try {
				response.getWriter().write(result);// 直接将完整的表单html输出到页面
				response.getWriter().flush();
			} catch (IOException e1) {
				e1.printStackTrace();
			}

		}
		// 初始化交易状态
		String statues = "退款失败";
		ModelAndView mv = new ModelAndView("forward:account.jsp");
		// 将获取到的交易结果json格式化
		JSONObject j = JSONObject.parseObject(result);
		// 取出json内容里面的值

		JSONObject j2 = JSONObject.parseObject(j.getString("alipay_trade_refund_response"));

		// 如果msg返回的值是success，则重新赋值给交易状态
		if ("Success".equals(j2.getString("msg"))) {
			statues = "退款成功";
			Orders order = os.getOrdersById(Integer.parseInt(out_trade_no));
			int userid = order.getUsers().getUserid();
			double integral = order.getOrderprice();
			// 减积分
			ms.updateMemberIntegerByUserid(userid, integral, "-");
			
		}
		mv.addObject("orderid",out_trade_no);
		
		mv.addObject("trade_status", statues);
		// 补充说明
		mv.addObject("trade_status_add", j2.getString("sub_msg"));
		return mv;
	}

	/**
	 * 同步通知的页面的Controller
	 */
	@RequestMapping("return_url")
	public ModelAndView Return_url() throws InterruptedException {

		Orders order = os.getOrdersById(orderid);
		// 修改订单信息：支付成功 + 支付时间
		Date now = new Date();
		order.setPaytime(now);
		order.setOrderstatus(1);
		// 同时生成了影票信息
		os.updOrders(order);

		// 根据orderid 获取影票信息
		List<Ticket> list = ts.getTicketByOrderid(orderid);
		HashMap<String, Object> map1 = new HashMap<>();
		// 处理座位的 2_1
 		String[] s1 = list.get(0).getSeat().split("_");
 		String seat1 = s1[0]+"排"+s1[1]+"座";
		
		if(list.size()>1) {
			// 有两张票
			map1.put("ticketid1", list.get(0).getTicketid());
			map1.put("seat1", seat1);
			String[] s2 = list.get(1).getSeat().split("_");
	 		String seat2 = s2[0]+"排"+s2[1]+"座";
			map1.put("ticketid2", list.get(1).getTicketid());
			map1.put("seat2", seat2);
			price = price / 2;
		}else {
			map1.put("ticketid1", list.get(0).getTicketid());
			map1.put("seat1", seat1);
		}
		
		// 电影名 放映时间 影厅 根据排期获取
		Schedule schedule = ss.selScheduleByid(scheduleid);
		HashMap<String, Object> map2 = new HashMap<>();
		// 处理时间 date
		SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String playtime = s.format(schedule.getPlaytime());
		map2.put("moviename",schedule.getMovies().getMoviename());
		map2.put("playtime", playtime);
		map2.put("hallname", schedule.getHall().getHallname());
		
		ModelAndView mv = new ModelAndView("forward:/PayFinal");
		
		mv.addObject("ticket",map1);
		mv.addObject("schedule", map2);
		mv.addObject("price", price);
		
		return mv;
	}
}
